<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
        <el-select
        clearable
        v-model="param.workCenter" 
        placeholder="请选择工作中心" 
        @focus="getCenterList" 
        style="margin-right:15px;margin-top:15px;width: 150px">
            <el-option 
            :value="item" 
            :label="item" v-for="(item,index) in this.centerList" 
            :key="index"/>
        </el-select>

        <el-date-picker
        v-model="param.year"
        type="year"
        placeholder="请选择年"
        value-format="yyyy"
        style="margin-right:15px;margin-top:15px;width: 150px">
        </el-date-picker>

        <el-date-picker
        v-model="param.month"
        type="month"
        value-format="MM"
        format="MM"
        placeholder="请选择月"
        style="margin-right:15px;margin-top:15px;width: 150px">
        </el-date-picker>

        <el-select
        clearable
        v-model="param.abnormalName"
        placeholder="请选择异常类型"
        style="margin-right:15px;margin-top:15px;width: 150px">
          <el-option
          :value="item"
          :label="item"
          v-for="(item,index) of this.typeList"
          :key="index"/>
        </el-select>

        <el-select
        clearable
        v-model="param.status"
        placeholder="请选择处理状态"
        style="margin-right:15px;margin-top:15px;width: 150px">
          <el-option
          :value="item"
          :label="item"
          v-for="(item,index) of this.statusList"
          :key="index"/>
        </el-select>

        <el-button style="margin-top:15px" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
            style="margin-top:15px"
        >
        取消</el-button>
    
    </div>
    <div style="display: flex;">
      <div ref="left" style="width: 820px; height: 300px;"></div>  
      <div ref="right" style="width: 570px; height: 300px;"></div>  
    </div>
    <el-link :underline="false" type="danger">注意：用年份搜索柱状图才是正确数据</el-link>
    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column label="序号" type="index" align="center" width="80px">
        <template v-slot="{ $index }">
          {{ (listQuery.page - 1) * listQuery.limit + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="机台号"  prop="machineId" align="center"/>
      <el-table-column label="异常工单号"  prop="planNo" align="center"/>
      <el-table-column label="异常类型"  prop="abnormalName" align="center"/>  
      <el-table-column label="异常小类"  prop="abnormalNameMin" align="center"/>  
      <el-table-column label="反馈时间"  prop="createTime" align="center" width="140px"/>
      <el-table-column label="处理时间"  prop="dealTime" align="center" width="140px"/>
      <el-table-column label="反馈人"  prop="userName" align="center"/>
      <el-table-column label="异常线体组长"  prop="dealUserName" align="center"/>
      <el-table-column label="处理状态" align="center" width="90px">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.status == '0'
                ? "未处理"
                : scope.row.status == '1'
                ? "已处理   ":"-"
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="责任人"  prop="setName" align="center"/>
      <el-table-column label="车间"  prop="departmentName" align="center"/> 
      <el-table-column label="线体"  prop="sectionName" align="center"/>
      <el-table-column label="异常描述"  prop="content" show-overflow-tooltip align="center"/>
      <el-table-column label="异常原因"  prop="dealContent" show-overflow-tooltip align="center"/>
      <el-table-column label="责任部门"  prop="dealWorkCenter" show-overflow-tooltip align="center"/>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { findSopErr, findSopErrDendrogram } from '../../api/errorList'
import { getCenter } from '../../api/workSection.js'
import * as echarts from 'echarts'
export default {
    name: 'sopErrorList',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                workCenter: '',                      //车间
                year: '',                           //年
                month: '',                          //月
                abnormalName: '',                   //异常类型
                status: ''
            },
            searchInputStyle: 'width: 150px;margin-right:15px;',
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            centerList: '',                         //工作中心列表
            typeList: [
                '工艺',
                '质量',
                '检验',
                '缺料',
                '设备',
                '来料',
                '模具',
                '计划',
                '数控',
                '焊接',
                '喷涂',
                '物控',
                '物流',
                '制造'
            ],
            statusList: [
                '未处理',
                '已处理'
            ],
            columnarList:[],
            color: ['#4f81bd','#c0504d','#9bbb59','#8064a2','#4bacc6','#f79646'],
            leftT: null,
            rightT: null,
            option: null
        }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.columnarList = []
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.workCenter){ query.workCenter = this.param.workCenter}
            if(this.param.year){ query.year = this.param.year}
            if(this.param.month){ query.month = this.param.month}
            if(this.param.abnormalName){ query.abnormalName = this.param.abnormalName}
            if(this.param.status){ query.status = this.param.status =='未处理'?0:1}
            let data = await findSopErr(query)
            let errmsg = data.msg
            if(data.code == '1'){
                this.total = data.data.count
                this.tableInfo = []
                data.data.list.forEach(item=>{
                    item.abnormalNameList.forEach(items => {
                        items.machineId = item.machineId
                    });
                    this.tableInfo = this.tableInfo.concat(item.abnormalNameList)
                })
                // 获取柱状图
                let obj = Object.assign({},query)
                delete obj.page
                delete obj.limit
                const res = await findSopErrDendrogram(obj)
                console.log('res',res)
                this.columnarList = res.data
                if(this.columnarList.length){
                  this.columnarList.forEach(item => {
                    item.abnormalType == 0
                    ? item.name = "工艺"
                    : item.abnormalType == 1
                    ? item.name = "质量"
                    : item.abnormalType == 2
                    ? item.name = "检验"
                    : item.abnormalType == 3
                    ? item.name = "缺料"
                    : item.abnormalType == 4
                    ? item.name = "设备"
                    : item.abnormalType == 5
                    ? item.name = "来料"
                    : item.abnormalType == 6
                    ? item.name = "模具"
                    : item.abnormalType == 7
                    ? item.name = "制造"
                    : item.abnormalType == 8
                    ? item.name = "计划"
                    : item.abnormalType == 9  
                    ? item.name = "物流":"-"

                    item.name == "工艺"
                    ? item.color = '#4f81bd'
                    : item.name == "质量"
                    ? item.color = '#c0504d'
                    : item.name == "计划"
                    ? item.color = '#9bbb59'
                    : item.name == "物流"
                    ? item.color = '#8064a2'
                    : item.name == "制造"
                    ? item.color = '#4bacc6'
                    : item.name == "设备"
                    ? item.color = '#f79646':"-"
                    const data = item.list.map(obj => obj.monthSum);
                    item.data = data
                    item.type = 'bar'
                    item.stack = 'Ad'
                    item.value = item.sum
                    item.emphasis ={ focus: 'series'}
                    delete item.abnormalType
                    delete item.list
                    delete item.sum
                  })
                }
                this.columnarList = this.columnarList.filter(item => {
                  if(item.color){
                    return true
                  }else{
                    return false
                  }
                })
                console.log('arr',this.columnarList)
                  this.rightMap()
                  this.left()
                this.loadingList = false
            } else {
                this.$message({
                    message: errmsg,
                    type: 'warning'
                })
            }
            this.loadingList = false
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = { 
            index: '序号',
            machineId: '机台号',
            planNo: '异常工单号',
            abnormalName:'异常类型',
            abnormalNameMin:'异常小类',
            createTime: '反馈时间',
            dealTime: '处理时间',
            userName: '反馈人',
            dealUserName: '异常线体组长',
            status: '处理状态',
            setName: '责任人',
            departmentName: '车间',
            sectionName: '线体',
            content: '异常描述',
            dealContent: '异常原因',
            dealWorkCenter: '责任部门',
            agingOfTreatment: '处理时效(H)',
            year: '年 ',
            month: '月',
            day: '日',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          console.log(props)
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          console.log(data)
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.workCenter){ query.workCenter = this.param.workCenter}
          if(this.param.year){ query.year = this.param.year}
          if(this.param.month){ query.month = this.param.month}
          if(this.param.abnormalName){ query.abnormalName = this.param.abnormalName}
          if(this.param.status){ query.status = this.param.status =='未处理'?0:1}
          let arr = await findSopErr(query)
          let arr2 = []
          arr.data.list.forEach(item=>{
            item.abnormalNameList.forEach(items => {
                items.machineId = item.machineId
            });
            arr2 = arr2.concat(item.abnormalNameList)
          })
          const { header, data } = this.transformDat(this.setSort(arr2))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '异常报表', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index + 1,
              machineId: item.machineId,
              planNo: item.planNo,
              abnormalName: item.abnormalName,
              abnormalNameMin: item.abnormalNameMin,
              createTime: item.createTime,
              dealTime: item.dealTime,
              userName: item.userName,
              dealUserName: item.dealUserName,
              status: item.status == 0?'未处理':item.status == 1?'已处理':'',
              setName: item.setName,
              departmentName: item.departmentName,
              sectionName: item.sectionName,
              content: item.content,
              dealContent: item.dealContent,
              dealWorkCenter: item.dealWorkCenter,
              agingOfTreatment: item.agingOfTreatment,  
              year: item.createTime.substring(0, 4) + '年',
              month: item.createTime.substring(5, 7) + '月',
              day: item.createTime.substring(8, 10) + '日',
            }
            arr1.push(obj)
          })
          return arr1
        },
        // 获取工作中心
        async getCenterList() {
          let {data} = await getCenter()
          this.centerList = data
        },
        cancelSubmit(){
            this.param = {
                workCenter: '',                      //车间
                year: '',                           //年
                month: '',                          //月
                abnormalName: '',                   //异常类型
                status: ''                          //处理状态
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        rightMap(){
          this.rightT = echarts.init(this.$refs.right);  
          // 指定图表的配置项和数据  
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{b} <br/> {c} ({d}%)'
            },
            grid: {
              width: '550px',
              height: '350px',
              containLabel: true
            },
            series: [
              {
                name:'1',
                type: 'pie',
                radius: '50%',
                data: this.columnarList,
                itemStyle: {
                    normal: {
                      color: function (params) {
                        if (params.name === '工艺') {  
                          return '#4f81bd'
                        } else if (params.name === '质量') {  
                          return '#c0504d'
                        } else if (params.name === '计划') {  
                          return '#9bbb59'
                        } else if (params.name === '物流') {  
                          return '#8064a2'
                        } else if (params.name === '制造') {  
                          return '#4bacc6'
                        } else if (params.name === '设备') {
                          return '#f79646'
                        }
                      }
                    },
                  }
              }
            ]
          };
          // 使用刚指定的配置项和数据显示图表。  
          this.rightT.setOption(option,true)
        },
        left(){
          this.leftT = echarts.init(this.$refs.left)
          // 基于准备好的dom，初始化echarts实例
           const option = {
              tooltip: {
                trigger: 'axis',
              },
               legend: {
                orient: 'vertical',
                bottom: '30%',
                right: '6%',
              },
              grid: {
                width: '650px',
                height: '300px',
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: [
                {
                  type: 'category',
                  data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                }
              ],
              yAxis: [
                {
                  type: 'value'
                }
              ],  
                series: this.columnarList,
            }
            this.leftT.setOption(option,true)
        }
    },
    // 进入页面获取table信息
    async mounted() { 
        await this.handleFilter()
    }
}
</script>

<style>

</style>